﻿using System.Data;
using System.Data.Entity;
using System.Linq;
using SQLLink.DomainClasses;

namespace SQLLink.DataLayer
{
    /// <summary>
    /// This is the context class
    /// </summary>
    public class Context:DbContext
    {
        public DbSet<GPRMC>   GPRMCs    { get; set; } //GPRMCs contained in the database
        public DbSet<BusLine> BusLines  { get; set; } //BusLines Contained in the database
        public DbSet<Bus>     Busses    { get; set; } //Busses contained in the database

        /// <summary>
        /// Reset()
        /// This method is used to reset the database contents
        /// </summary>
        public void Reset()
        {
            //It sets all the GPRMCs to deleted
            foreach (var gprmc in GPRMCs)
            {
                Entry(gprmc).State = EntityState.Deleted;
            }

            //It sets all the busses to deleted
            foreach (var bus in Busses)
            {
                Entry(bus).State = EntityState.Deleted;
            }

            //It sets all the buslines to deleted
            foreach (var busLine in BusLines)
            {
                Entry(busLine).State = EntityState.Deleted;
            }
            try
            {
                //It saves the changes
                SaveChanges();
            }   
            catch
            {
                //Do nothing
            }
        }

        /// <summary>
        /// UpdateBusLine(int)
        /// This methods is used to update a busline database content
        /// </summary>
        /// <param name="busLineNumber">the busline to update</param>
        public void UpdateBusLine(int busLineNumber)
        {
            var busses = (from b in Busses where b.LineNumber == busLineNumber select b).ToList();

            foreach (var bus in busses)
            {
                var gprmcs = (from g in GPRMCs where g.ParentBus.LineNumber == bus.LineNumber select g);
                foreach (var gprmc in gprmcs)
                {
                    if (bus.GPRMCs.Count > 0 && gprmc == bus.GPRMCs.Last())
                    {
                        Entry(gprmc).Reload();
                    }
                }
            }
        }

        /// <summary>
        /// GetBusLine(int)
        /// This method is used to get a busline from the database
        /// </summary>
        /// <param name="busLineNumber">The bus line number to look for in the database</param>
        /// <returns>The specified busline, or null if it wasn't found</returns>
        public BusLine GetBusLine(int busLineNumber)
        {
            UpdateBusLine(busLineNumber);
            return (from b in BusLines where b.Number == busLineNumber select b).FirstOrDefault();
        }
    }
}